package stc.skymobi.app.commons.test;

import io.netty.channel.ChannelHandlerContext;
import stc.skymobi.netty.handler.codec.http.HttpResponseHandler;
import stc.skymobi.util.Identifyable;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.collections.Closure;

public class RequestCallback extends HttpResponseHandler implements Closure {
    private static final Map<UUID, Identifyable> responseMap = new HashMap<UUID, Identifyable>();
    private static final Map<UUID, CountDownLatch> lockMap = new HashMap<UUID, CountDownLatch>();

    @Override
    public void execute(Object input) {
    	Identifyable identifyable = (Identifyable) input;
        UUID uuid = identifyable.getIdentification();
        try {
            responseMap.put(uuid, identifyable);
        } finally {
            lockMap.remove(uuid).countDown();
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Identifyable response = (Identifyable) msg;
        execute(response);
    }

    @SuppressWarnings("unchecked")
    public <T extends Identifyable> T getResponse(UUID uuid) {
        CountDownLatch lock = new CountDownLatch(1);
        lockMap.put(uuid, lock);
        try {
            lock.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return (T) responseMap.remove(uuid);
    }
}